import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mahjong/const/BusinessEnum.dart';
import 'package:mahjong/handler/mahjong/MessageInteractive.dart';
import 'package:mahjong/page/GameIndex.dart';
import 'package:mahjong/const/MahjongSystemConst.dart';
import 'package:mahjong/handler/mahjong/MessageOffline.dart';
import 'package:mahjong/handler/mahjong/AbstractMessageHandler.dart';
import 'package:mahjong/handler/mahjong/MessageCardBar.dart';
import 'package:mahjong/handler/mahjong/MessageCardExport.dart';
import 'package:mahjong/handler/mahjong/MessageCardHu.dart';
import 'package:mahjong/handler/mahjong/MessageCardTouch.dart';
import 'package:mahjong/handler/mahjong/MessageReadHomeHandler.dart';
import 'package:mahjong/handler/mahjong/MessageCardLicensing.dart';
import 'package:mahjong/handler/mahjong/MessageOnLine.dart';
import 'package:mahjong/handler/Mahjong/MessageDiskDice.dart';
import 'package:mahjong/handler/mahjong/MessageCardCall.dart';
import 'package:mahjong/handler/mahjong/MessageActionTips.dart';
import 'package:mahjong/handler/mahjong/MessageDissolution.dart';
import 'package:mahjong/handler/mahjong/MessageCardExchange.dart';
import 'package:mahjong/handler/mahjong/MessageUserUpdate.dart';
import 'package:mahjong/handler/mahjong/MessageUserPrepare.dart';
import 'package:mahjong/page/mahjong/CurrentGameWidget.dart';
import 'package:mahjong/page/mahjong/LeftGameWidget.dart';
import 'package:mahjong/page/mahjong/RightGameWidget.dart';
import 'package:mahjong/page/mahjong/TopGameWidget.dart';
import 'package:mahjong/util/CommonDialog.dart';
import 'package:mahjong/util/CustomNavigatorObserver.dart';
import 'package:mahjong/util/CustomRoute.dart';
import 'package:mahjong/util/CustomerDialog.dart';
import 'package:mahjong/util/MessageUtils.dart';
import 'package:mahjong/entity/MessageContext.dart';
import 'package:mahjong/const/MahjongConst.dart';
import 'package:mahjong/page/mahjong/BillClearing.dart';
import 'package:mahjong/widget/MahjongDataTips.dart';
import 'package:mahjong/widget/dialog/PopupMenu.dart';
import 'DiceWidget.dart';
import 'Settlement.dart';

class MahjongGameIndex extends StatefulWidget {
  final String url;
  MahjongGameIndex(this.url);
  @override
  _MahjongGameIndexState createState() => _MahjongGameIndexState();
}

class _MahjongGameIndexState extends State<MahjongGameIndex>
    with WidgetsBindingObserver {
  Map<String, AbstractMessageHandler> handler = {};
  Timer socketTimer;

  void initAction() {
    handler[UserActionConst.OFF_LINE] = MessageOffline();
    handler[UserActionConst.ON_LINE] = MessageOnline();
    handler[MessageAction.READ_HOME] = MessageReadHomeHandler();
    handler[MessageAction.CARD_CALL] = MessageCardCall();
    handler[MessageAction.CARD_LICENSING] = MessageCardLicensing();
    handler[MessageAction.EXPORT_CARD] = MessageCardExport();
    handler[MessageAction.DISK_DICE] = MessageDiskDice();
    handler[MessageAction.ACTION_TIPS] = MessageActionTips();
    handler[MessageAction.CARD_BAR] = MessageCardBar();
    handler[MessageAction.CARD_TOUCH] = MessageCardTouch();
    handler[MessageAction.CARD_HU] = MessageCardHu();
    handler[MessageAction.USER_PREPARE] = MessageUserPrepare();
    handler[MessageAction.EXCHANGE_CARD] = MessageCardExchange();
    handler[MessageAction.USER_UPDATE] = MessageUserUpdate();
    handler[MessageAction.DISSOLUTION] = MessageDissolution();
    handler[MessageAction.INTERACTIVE] = MessageInteractive();
  }

  void doMessage() {
    MessageUtils.connect((result) {
      var messageContext =
          MessageContext<dynamic>.fromJson(json.decode(result));
      try {
        if (messageContext.code == BusinessEnum.roomNotFound ||
            messageContext.code == BusinessEnum.roomFull) {
          Navigator.of(context).pushAndRemoveUntil(
              new CustomRoute(GameIndex(), AnimationEnum.zoom),
              (route) => route == null);
          CustomerDialog.showText(messageContext.body,
              bottomColor: Colors.orange);
        } else if (messageContext.code == BusinessEnum.error) {
          CustomerDialog.showText(messageContext.body,
              bottomColor: Colors.orange);
        }
        // 当服务器收到退出指令的 时候 会主动回调
        if (messageContext.action == MessageAction.LOG_OUT) {
          Navigator.of(context).pushAndRemoveUntil(
              new CustomRoute(GameIndex(), AnimationEnum.zoom),
              (route) => route == null);
        }
        if (messageContext.action != null) {
          var doHandler = handler[messageContext.action];
          doHandler.doMessage(messageContext);
        }
      } on Exception {
        print("找不到需要处理的方法....");
      } catch (e) {
        print(e);
        print("找不到需要处理的方法...." + messageContext.action);
      }
    }, widget.url);
  }
  /** 
   * 当 app退出的时候 不管 是否后台运行 都要通知其它用户 这个用户 离线了
   */

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.inactive:
        MessageUtils.closeSocket();
        socketTimer.cancel();
        break;
      case AppLifecycleState.resumed: // 应用程序可见，前台
        initSocketTimer();
        break;
      case AppLifecycleState.paused: // 应用程序不可见，后台
        MessageUtils.closeSocket();
        socketTimer.cancel();
        break;
      case AppLifecycleState.detached: // 申请将暂时暂停
        MessageUtils.closeSocket();
        socketTimer.cancel();
        break;
    }
    super.didChangeAppLifecycleState(state);
  }

  void initSocketTimer() {
    doMessage();
    socketTimer =
        new Timer.periodic(new Duration(seconds: 5), (Timer timer) async {
      if (MessageUtils.webSocket == null) {
        doMessage();
      }
    });
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      diskPartUserProvider.clear();
      initSocketTimer();
    });

    diceStreamController = StreamController();
    exchangeCardStreamController = StreamController();
    initAction();
  }

  @override
  void dispose() {
    diceStreamController?.close();
    exchangeCardStreamController?.close();
    socketTimer?.cancel();
    MessageUtils.closeSocket();
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Stack(children: [
      // 背景
      Positioned(
          child: Container(
        width: double.infinity,
        child: Image.asset(
          "images/mahjong/background/home_bg2.jpg",
          fit: BoxFit.fill,
        ),
      )),
      mahjongCenter(),
      DiceWidget(),
      TopGameWidget(),
      RightGameWidget(),
      LeftGameWidget(),
      // 当前用户的UI
      CurrentGameWidget(),
      MahjongDataTips(),
      Settlement(),
      BillClearing(title: "战绩总览", description: ".........."),
    ]));
  }

  Positioned mahjongCenter() {
    return Positioned(
      top: ScreenUtil().screenHeight / 2 - MahjongSystemConst.centerLRBT / 2,
      left: ScreenUtil().screenWidth / 2 - MahjongSystemConst.centerLRBT / 2,
      child: Container(
        width: MahjongSystemConst.centerLRBT,
        height: MahjongSystemConst.centerLRBT,
        padding: EdgeInsets.all(MahjongSystemConst.centerLRBT / 8),
        //设置背景图片
        decoration: new BoxDecoration(
          image: new DecorationImage(
            image: new AssetImage("images/mahjong/background/center.png"),
            centerSlice: new Rect.fromLTRB(270.0, 180.0, 1360.0, 730.0),
          ),
        ),
        /*  child: Stack(
          children: [
            Align(
                alignment: Alignment.topCenter,
                child: Text(
                  "东",
                  style:
                      TextStyle(color: Colors.white, fontSize: 9.sp, height: 1),
                )),
            Align(
                alignment: Alignment.bottomCenter,
                child: Text(
                  "南",
                  maxLines: 1,
                  style:
                      TextStyle(color: Colors.white, fontSize: 9.sp, height: 1),
                )),
            Align(
                alignment: Alignment.centerLeft,
                child: Text(
                  "西",
                  style:
                      TextStyle(color: Colors.white, fontSize: 9.sp, height: 1),
                )),
            Align(
                alignment: Alignment.centerRight,
                child: Text(
                  "北",
                  style:
                      TextStyle(color: Colors.white, fontSize: 9.sp, height: 1),
                )),
          ],
        ), */
      ),
    );
  }
}

class MahjongMenu extends StatefulWidget {
  const MahjongMenu({
    Key key,
  }) : super(key: key);
  @override
  _MahjongMenuState createState() => _MahjongMenuState();
}

class _MahjongMenuState extends State<MahjongMenu> {
  bool _ischeck = false;
  @override
  Widget build(BuildContext context) {
    return PopupMenu(
      childOnTap: () {
        setState(() {
          _ischeck = !_ischeck;
        });
      },
      onValueChanged: (int value) {
        switch (value) {
          case 0:
            CommonDialog.showConfirmDialog(
                confirm: () {
                  // 发送退出指令
                  MessageContext message =
                      new MessageContext(action: MessageAction.LOG_OUT);
                  MessageUtils.sendMessage(message.toString());
                },
                tips: "退出房间吗?");
            break;
          case 1:
            CommonDialog.showConfirmDialog(
                confirm: () {
                  MessageContext message =
                      new MessageContext(action: MessageAction.DISSOLUTION);
                  message.body = RoomDissolutionConst.agree;
                  if (MessageUtils.sendMessage(message.toString())) {
                    Navigator.of(CustomNavigatorObserver.getContext()).pop();
                  }
                },
                tips: "申请解散吗?");
            break;
          default:
            break;
        }
      },
      pressType: PressType.singleClick,
      backgroundColor: Colors.white,
      direction: Axis.vertical,
      gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [Colors.white],
          stops: [1]),
      menuHeight: 30.h,
      menuWidth: 110.w,
      actions: [
        buildMenuItem(Icons.exit_to_app, "退出房间"),
        buildMenuItem(Icons.delete_sweep, "申请解散"),
        buildMenuItem(Icons.settings, "房间设置"),
      ],
      child: ClipOval(
        child: Container(
          padding: EdgeInsets.all(5.h),
          decoration: BoxDecoration(color: Colors.white.withOpacity(0.3)),
          child: Icon(
            _ischeck ? Icons.menu_open : Icons.menu,
            color: Colors.white,
            size: 15.h,
          ),
        ),
      ),
    );
  }

  Row buildMenuItem(IconData icon, String itemName) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        Icon(
          icon,
          color: Colors.black,
          size: 15.h,
        ),
        Text(
          itemName,
          style: TextStyle(color: Colors.black, fontSize: 14.sp),
        )
      ],
    );
  }
}
